import json
import time

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer
from channels.layers import get_channel_layer
import datetime


class LogsConsumerSync(WebsocketConsumer):
    """
    涉及ORM操作使用同步方式
    """

    # websocket建立连接时执行方法
    def connect(self):
        print("scope:", self.scope)
        # 从url里获取聊天室名字，为每个房间建立一个频道组
        self.id = self.scope['url_route']['kwargs']['id']  # 获取传输的房间Id
        self.room_name = 'logs_%s' % self.id  # 添加分组名以chat_开头

        # 接受所有websocket请求
        self.accept()

        # while 1:
        #     print(time.time())
        #     self.send(text_data=str(time.time()))
        #     time.sleep(5)

        if self.id == "a123":
            print('id=', self.id)
            fname = "./apps/websocket/django.log"
        else:
            fname = "./apps/websocket/20210930_94MXvc3XUsNLfkDsKBVGUH.log"
        with open(fname, encoding='utf-8') as f:
            for line in f:
                self.send(text_data=line)
            self.send("Success")



def get_deploy_logs(id):
    channels_layer = get_channel_layer()
    channels_layer.send()
    pass